package inc;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CommonFunction {
	
	public static String cookie_page_name = "pageUrl"; //remember the current page's cookie name
	/*
	 *  this function will add a cookie, parameter time is the second unit
	 */
	
	public String xmlAppend(String xml, String fatherNode, String nodeName, Object nodeValue){
        if(nodeValue==null){
            nodeValue = "";
        }
		if(xml==null || fatherNode==null || !xml.contains("<")) {
			xml = "<" + nodeName + ">" + nodeValue + "</" + nodeName + ">";
			return xml;
		}
		String fatherStr = "<" + fatherNode + ">";
		int  fatherBegin = xml.indexOf(fatherStr);
		if(fatherBegin < 0) {
			return null;
		}
		xml = xml.substring(0, fatherBegin + fatherStr.length()) + "<" + nodeName + ">" + nodeValue + "</" + nodeName + ">" +
							xml.substring(fatherBegin + fatherStr.length() , xml.length());
		return xml;
	}
	//ajax return response text
	public String ajaxPrint(HttpServletResponse resp, String contentType, String encoding, String responseText){
        if("JSON".equals(contentType.toUpperCase())){
            contentType = "application/json";
        }else if("XML".equals(contentType.toUpperCase())){
            contentType = "text/xml";
        }else{
            contentType = "text/html";
        }
		encoding = encoding!=null ? encoding : "utf-8";
		resp.setContentType(contentType);   
		resp.setCharacterEncoding(encoding);
	    resp.setHeader("Cache-Control", "no-cache");   
		PrintWriter out = null;
		try {
			out = resp.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.print(responseText);
		out.close();
		return responseText;
	}
	
	//get print writer
	public PrintWriter getOut(HttpServletResponse resp){
		resp.setContentType("text/xml");   
		resp.setCharacterEncoding("utf-8");
	    resp.setHeader("Cache-Control", "no-cache");   
		PrintWriter out = null;
		try {
			out = resp.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return out;
	}
	
	// get value from string like: name=lewdy&age=22&adrress=china ...
	public String getParameter(String sourceStr, String paraName, String symbol)  {
		String temp = sourceStr;
		if(temp.indexOf(paraName) < 0) 
			return null;
		int begin = temp.indexOf(paraName) ;
		temp = temp.substring(begin, temp.length());
		temp = temp.substring(temp.indexOf("=") + 1, 
				temp.indexOf(symbol)>0 ? temp.indexOf(symbol) : temp.length());
		return temp;
	}
	
	public void addCookie(HttpServletRequest req, HttpServletResponse resp, String name, String value, int time) {
		Cookie c = new Cookie(name, value); 
		c.setMaxAge(time);
		resp.addCookie(c); 
	}
	
	//get a cookie by name
	public Cookie getCookie(HttpServletRequest req, HttpServletResponse resp, String name) {
		Cookie[] cs = req.getCookies();
		for(int i=0; i<cs.length; i++) {
			if(cs[i].getName().equals(name)) {
				return cs[i];
			}
		}
		return null;
	}
	
	//mark a member login
	public void markLogin(HttpServletRequest req, int mid, String username) {
		req.getSession().setAttribute("mid", mid);
		req.getSession().setAttribute("username", username);
	}
	
	//get logined member id
	public int getLoginedMid(HttpServletRequest req) {
		return req.getSession().getAttribute("mid")!=null
			? (Integer)req.getSession().getAttribute("mid")
			: 0;
	}
	
	public boolean isLogin(HttpServletRequest req) {
		return req.getSession().getAttribute("mid")!=null
			? true
			: false;
	}
	
	public String getLoginedUsername(HttpServletRequest req) {
		return req.getSession().getAttribute("username")!=null
			? (String)req.getSession().getAttribute("username")
			: "0";
	}
	
	//quit login
	public void loginQuit(HttpServletRequest req) {
		req.getSession().removeAttribute("mid");
		req.getSession().removeAttribute("username");
	}
	
	//encrypt password
	public String encryptPassword(String str) {
		return MD5andKL.MD5(str);
	}
	
	//按日期新建文件夹
	public String createDateDir(String basePath) {
		SimpleDateFormat sdf;
		Date date = new Date();
		if(!basePath.endsWith("/") && basePath.length()>0) {
			basePath += "/";
		}
		sdf = new SimpleDateFormat("yyyy");
		basePath += sdf.format(date) + "/";
		File yearDir = new File(basePath);
		if(!yearDir.isDirectory()) {
			yearDir.mkdir();
		}
		sdf = new SimpleDateFormat("MM");
		basePath += sdf.format(date) + "/";
		File monthDir = new File(basePath);
		if(!monthDir.isDirectory()) {
			monthDir.mkdir();
		}
		sdf = new SimpleDateFormat("dd");
		basePath += sdf.format(date) + "/";
		File dayDir = new File(basePath);
		if(!dayDir.isDirectory()) {
			dayDir.mkdir();
		}
		
		return basePath;
	}
	
	//get File Name's Extension
	public String getFileNameExtension(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
	}
	
	//控制浮点型精�?
	/*
	 * scale，小数点后保留的位数
	 * roundingMode, BigDecimal.ROUND_DOWN | BigDecimal.ROUND_UP
	 */
	public double round(double value, int scale, int roundingMode) {
		BigDecimal bd = new BigDecimal(value);
		bd = bd.setScale(scale, roundingMode);
		double d = bd.doubleValue();
		bd = null;
		return d;
	}
	
	public static void main(String args[]) {
		CommonFunction fun = new CommonFunction();
		//System.out.println(fun.encryptPassword("aa"));
		//System.out.println(fun.createDateDir("D:/"));
		//System.out.println(fun.getFileNameExtension("wefwef.jpg"));
//		String  xml = "<data><msg>OK<msg></data>";
//		xml = fun.xmlAppend(xml, "data", "success", "000");
//		System.out.println(xml);
		//e10adc3949ba59abbe56e057f20f883e
		System.out.println(fun.encryptPassword("123456"));
	}
	
}
